/*
 * Dijjer - A Peer to Peer HTTP Cache
 * Copyright (C) 2004,2005 Change.Tv, Inc
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
package dijjer.io.comm;

import java.net.DatagramPacket;
import dijjer.updater.ResourceManager;
import dijjer.util.AbstractThread;
import dijjer.util.Misc;
import dijjer.util.logging.Logger;

public class UdpSocketManager extends AbstractThread {

	public static final String VERSION = "$Id: UdpSocketManager.java 2 2008-03-21 14:33:03Z ian.clarke $";
	private Dispatcher _dispatcher;
	private int _dropProbability = 0;
	private boolean _isDone = false;
	private static UdpSocketManager _usm;
	private final int _listenPort;

	public UdpSocketManager(int listenPort) throws Exception {
		_listenPort = listenPort;
		startThread();
		getBaseThread().setName("UdpSocketManager sender thread on port " + listenPort);
	}

	protected boolean loop() throws InterruptedException { // Listen for packets
		DatagramPacket packet = ResourceManager.receive(_listenPort);

		// Check for matched _filters
		if (packet != null) {
			checkFilters(packet);
		}
		return true;
	}

	protected void cleanUp() {
		synchronized (this) {
			_isDone = true;
			notifyAll();
		}
	}

	private void checkFilters(DatagramPacket packet) {
		Message m = null;
		try {
			m = Message.decodeFromPacket(packet);
		} catch (Exception e) {
			e.printStackTrace();
			Logger.error("Couldn't parse packet from " + packet.getAddress());
			return;
		}
		if (m == null) {
			return;
		}

		if (m.getSpec().equals(DMT.ping) || m.getSpec().equals(DMT.pong)) {
			//no more ping pong
		} else if (m.getSpec().equals(DMT.packetTransmit)) {
			Logger.debug(Logger.getCommString(_listenPort,true,m.getSource(),m));
		} else {
			Logger.info(Logger.getCommString(_listenPort,true,m.getSource(),m));
		}

		boolean matched = MessageFilter.checkFilters(m);
		// Feed unmatched messages to the dispatcher
		if (!matched && (_dispatcher != null)) {
			try {
				matched = _dispatcher.handleMessage(m);
			} catch (Exception e) {
				Logger.error("Error handling message: "+ m, e);
			}
		}
		if (!matched) matched = MessageFilter.checkFilters(m);
		// Keep the last few _unclaimed messages around in case the intended receiver isn't receiving yet
		if (!matched) {
			Logger.info("Received unclaimed message "+m+", adding to unclaimed pile");
		MessageFilter.addUnclaimed(m);
		}
	}

	public Message waitFor(MessageFilter filter) {
		filter.match();
		return filter.getMessage();
	}

	public void send(Peer destination, Message m) {
		if (_dropProbability > 0) {
			if (Misc.nextInt() % _dropProbability == 0) {
				Logger.info("DROPPED: " + _listenPort + " -> " + destination.getPort() + " : " + m);
				return;
			}
		}
		
		if (m.getSpec().equals(DMT.ping) || m.getSpec().equals(DMT.pong)) {
			// no more ping pong
		} else if (m.getSpec().equals(DMT.packetTransmit)) {
			Logger.debug(Logger.getCommString(_listenPort,false,destination,m));
		} else {
			Logger.info(Logger.getCommString(_listenPort,false,destination,m));
		}
		
		DatagramPacket packet = m.encodeToPacket();
		packet.setAddress(destination.getAddress());
		packet.setPort(destination.getPort());
		ResourceManager.send(_listenPort, packet);
	}

	public void shutdown(boolean exit) {
		synchronized (this) {
			while (!_isDone) {
				try {
					wait(2000);
				} catch (InterruptedException e) {
					Logger.error(e);
				}
			}
		}
	}

	public void setDispatcher(Dispatcher d) {
		_dispatcher = d;
	}

	public String toString() {
		return ResourceManager.getUDPSocketString(_listenPort);
	}

	public void setDropProbability(int dropProbability) {
		_dropProbability = dropProbability;
	}

	public static UdpSocketManager getUdpSocketManager()
	{
		return _usm;
	}

	public static void init(int externalListenPort)
	    throws Exception
	{
		_usm = new UdpSocketManager(externalListenPort);
	}
}
